<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { FormSchema } from '@/components/Form'
import { Table, TableColumn } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive, computed } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { BaseButton } from '@/components/Button'
import { CalculateCellWidth } from '@/utils/calculateCellWidth'
import { getDictPageApi, deleteDictApi, updateDictApi, createDictApi } from '@/api/dict'
import { CreateDictData, DictPageResponse, DictUpdateData } from '@/api/dict/types'
import { Log } from '@/utils/logError'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const { data, pagination } = await getDictPageApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: data,
      total: pagination?.total || 0
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const actionWidth = computed(() =>
  CalculateCellWidth([
    { permission: 'dicts:update', width: 86 },
    { permission: 'dicts:detail', width: 86 },
    { permission: 'dicts:delete', width: 86 }
  ])
)

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('common.tableIndex'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('dict.name'),
    slots: {
      default: (data: any) => {
        return <>{data.row.name}</>
      }
    }
  },
  {
    field: 'code',
    label: t('dict.code')
  },
  {
    field: 'status',
    label: t('common.status'),
    slots: {
      default: (data: any) => {
        const status = data.row.status
        return (
          <>
            <ElTag type={status ? 'success' : 'danger'}>
              {status ? t('common.enable') : t('common.disable')}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'isSystem',
    label: t('dict.isSystem'),
    slots: {
      default: (data: any) => {
        const status = data.row.isSystem
        return (
          <>
            <ElTag type={status ? 'primary' : 'danger'}>
              {status ? t('common.yes') : t('common.no')}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'description',
    label: t('common.remark')
  },
  {
    field: 'action',
    label: t('common.action'),
    width: actionWidth.value,
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton
              type="primary"
              v-prem={{ value: 'dicts:update' }}
              onClick={() => action(data.row, 'edit')}
            >
              {t('common.edit')}
            </BaseButton>
            <BaseButton
              type="success"
              v-prem={{ value: 'dicts:detail' }}
              onClick={() => action(data.row, 'detail')}
            >
              {t('common.detail')}
            </BaseButton>
            <BaseButton
              type="danger"
              disabled={data.row.isSystem}
              v-prem={{ value: 'dicts:delete' }}
              onClick={() => delData(data.row)}
            >
              {t('common.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'keyword',
    label: t('dict.keyword'),
    component: 'Input'
  },
  {
    field: 'status',
    label: t('common.status'),
    component: 'Select',
    componentProps: {
      options: [
        {
          label: t('common.enable'),
          value: true
        },
        {
          label: t('common.disable'),
          value: false
        }
      ]
    }
  }
])
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DictPageResponse | null>(null)
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const action = (row: DictPageResponse, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('common.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: DictPageResponse) => {
  try {
    await ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
      confirmButtonText: t('common.delOk'),
      cancelButtonText: t('common.delCancel'),
      type: 'warning'
    })
      .then(async () => {
        delLoading.value = true
        await deleteDictApi(row.code)
        await getList()
        ElMessage.success(t('common.delSuccess'))
      })
      .catch(() => {})
      .finally(() => {
        delLoading.value = false
      })
  } catch (error) {
    Log.error('delData', error)
  }
}

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (!formData) return ElMessage.error('请填写完整')
  const deleteKeys = ['children', 'createdAt', 'updatedAt']
  deleteKeys.forEach((key) => {
    delete formData[key]
  })
  try {
    saveLoading.value = true
    await (actionType.value === 'add'
      ? createDictApi(formData as CreateDictData)
      : updateDictApi(formData as DictUpdateData))
    dialogVisible.value = false
    currentPage.value = 1
    await getList()
  } catch (error) {
    Log.error('save', error)
  } finally {
    saveLoading.value = false
  }
}
</script>

<template>
  <ContentWrap v-prem="'dicts:page'">
    <Search :schema="searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" v-prem="'dicts:create'" @click="AddAction">
        {{ t('common.add') }}
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail v-else :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('common.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('common.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
